/**
 * Setvor project
 */
package setvor.yeild;

import java.util.*;

/**
 * @author julatec
 *
 */
class FilterIterator<T> implements Iterator<T> {
	
	private T value;
	
	private Iterator<T> iterator;
	
	private boolean hasNextTested;
	
	public FilterIterator(Filter<T> filter, Iterator<T> iterator){
		super();		
		this.iterator = iterator;
		hasNextTested = false;
		filters = new Vector<Filter<T>>();
		this.filters.add(filter);
	}
	
	private List<Filter<T>> filters;
	
	private boolean accept(T value){
		for(Filter<T> filter : this.filters)
			if(!filter.accept(value))
				return false;
		return true;
	}
	
	@Override
	public boolean hasNext() {
		hasNextTested = true;
		while(iterator.hasNext())
			if(accept(this.value = iterator.next()))
				return true;
		return false;
	}

	@Override
	public T next() {
		if(!(hasNextTested || hasNext()))
			throw new NoSuchElementException();
		hasNextTested = false;
		return value;
	}

	@Override
	public final void remove() {		
	}
	
	public void addFilter(Filter<T> newFilter){
		filters.add(newFilter);
	}
	
	public String toString(){
		StringBuilder filterString = new StringBuilder();
		boolean first = true;
		for(Filter<T> filter : filters){
			filterString.append((first ? "" : " and ") + filter);
			first = false;
		}
		return "{FilterIterator:" + iterator + " filter by " + filterString +"}";
	}

}
